<?php
// +----------------------------------------------------------------------
// | 奇乐中介担保交易系统 免费版 2019
// +----------------------------------------------------------------------
// | 官方网址：http://www.qilecms.com   
// +----------------------------------------------------------------------
// | 产品文档：http://www.qilecms.com/doc
// +----------------------------------------------------------------------
// | 开发作者: 奇乐CMS
// +----------------------------------------------------------------------
// | 版权说明：这不是一个自由软件！本产品仅限个人使用，但请务必保留底部版权，以免产生不必要的纠纷,
// | 您只能在不用于商业目的的前提下对程序代码进行修改和使用，
// | 任何企业和个人不允许对程序代码以任何形式任何目的再发布。
// +----------------------------------------------------------------------
namespace app\admin\controller;
use think\controller;
use think\Db;
class Guarantee extends Category
{


	public function index()
  {
      $alias = 'a';        //需要别名时写别名，不需要的时候留空 
      $param = $this->request->param();
      if($this->request->isPost()){
         $status = isset($param['SingleField'][0]['value'])?$param['SingleField'][0]['value']:'-1';
      }else{
        $status = isset($param['status'])?$param['status']:'-1';
      }
     
  switch($status) {
   
        case '0':
        //待确认
             $defaultWhere =" a.order_status = 0 and a.pay_status = 0 and a.shipping_status = 0";
            break;
        case '1':
        // 待付款
            $defaultWhere =" a.order_status = 1 and a.pay_status = 0 and a.shipping_status = 0";
            break;
        case '2':
        // 待发货
            $defaultWhere =" a.order_status = 1 and a.pay_status = 1 and a.shipping_status = 0 ";
            break;
        case '3':
        // 待验收
            $defaultWhere =" a.order_status = 1 and a.pay_status = 1 and a.shipping_status = 1";
            break;
        case '4':
       // 交易完成
            $defaultWhere =" a.order_status = 1 and a.pay_status = 1 and a.shipping_status = 2";
            break;
        case '5':
             // 订单关闭
        $defaultWhere     =" a.order_status = 2 and a.pay_status = 0 and a.shipping_status = 0";
            break;
        default:
         $defaultWhere     = '';
       
    }

      $defaultOrder = 'a.create_time desc';  //默认排序
    //接收搜索表单数据
      $SearchFormData = $this->getSearchFormData($defaultWhere,$defaultOrder);
      $where = $SearchFormData['where'];
      
      $order = $SearchFormData['order'];
      $pageNum = $SearchFormData['pageNum'];
//组建关键词数据
     $keywordsData  =[
                  [
                  'field'   =>'id', //字段名
                  'name'    =>'订单ID', //文本显示名称
                  'alias'   => $alias,  //字段对应的别名
                  ],
                  [
                  'field'   =>'title',
                  'name'    =>'订单标题',
                  'alias'   => $alias,
                  ],
                  [
                  'field'   =>'buyer',
                  'name'    =>'买家',
                  'alias'   => $alias,
                  ],
                  [
                  'field'   =>'seller',
                  'name'    =>'卖家',
                  'alias'   => $alias,
                  ]
     ];
//组建日期筛选   
       $dateData = [
                  [
                  'title'        =>'创建时间',  //标签显示名称
                  'field'        =>'create_time', //筛选字段
                  'start_name'   =>'开始时间', //开始时间
                  'end_name'     =>'结束时间', //结束时间
                  'alias'        => $alias,  //字段别名
                  ],

              ];
//单个字段筛选
    $customSingleField =[
                            [
                             'name'=>'订单状态',
                             'field' => 'status', 
                             'data'  => [ 0 =>'待确认',1=>'待付款',2=>'待发货',3=>'待验收',4=>'交易成功',5=>'交易关闭'],
                             'alias'=>$alias,
                              'query' =>1,
                            ]
                       ]; 
// 组件字段组筛选
    $groupData = [];
    $orderData   = [
                 [
                 'name'     =>'价格多到少',
                 'field'    =>'price',  //字段名
                 'orderby'  =>'desc',     //注册排序
                 'alias'    => $alias,         //数据表别名
                 ],
                 [
                 'name'     =>'价格少到多',
                 'field'    =>'price',
                 'orderby'  =>'asc',
                 'alias'    => $alias,
                 ],
];  

     $this->assign('keywordsData',$keywordsData);
     $this->assign('customSingleField',$customSingleField);
     $this->assign('groupData',$groupData);
     $this->assign('dateData',$dateData);
     $this->assign('orderData',$orderData);


     $list = DB::name('guarantee')->alias('a')

     ->join("guarantee_category b","a.cid = b.cid","LEFT")
     ->field("a.id,a.title,a.price,a.fee_ratio,a.buyer,a.create_time,a.seller,a.buyer_evaluate,a.seller_evaluate,a.order_status,a.pay_status,a.shipping_status,b.cname,a.cid")
     ->where($where)
     ->order($order)
     ->paginate($pageNum,false,['query' => request()->param()]);

     $page = $list->render();
     $this->assign('page', $page);
     $this->assign('list', $list->toArray()['data']);
     return $this->fetch();
	}
//创建中介交易
	public function add()
  {

     if($this->request->isPost()){
             $param = input();

               //表单验证
               $rule =[
                  'cid'=>'require',
                  'title'=>'require',
                  'buyer'=>'require',
                  'seller'=>'require',
                  'price'=>'require',
                  'fee_type'=>'require',
                  'buyer_pay'=>'require',
                  'seller_get'=>'require',
                  'content'=>'require',
                ];
                $msg= [
                'cid.require' =>'交易分类不能为空',
                 'title.require' =>'交易标题不能为空',
                 'buyer.require' =>'买家不能为空',
                 'seller.require' =>'卖家不能为空',
                 'price.require' =>'交易价格不能为空',
                 'fee_type.require' =>'交易方式不存在',
                 'buyer_pay.require' =>'买家实际支付金额不能存在',
                 'seller_get.require' =>'卖家实际获得金额不能存在',
                 'content.require' =>'内容不能为空',
                
                ];

                 $error = $this->checkSubmit($param,$rule,$msg);  
                 
                if($error){
                    return error_json($error);
                 }
          //判断买家是否存在
            $map['username'] = $param['buyer'];
            $buyer = model('user')->infoData($map);
            if(empty($buyer)){
              return error_json('买家不存在');
            }

          // 判断卖家是否存在
              $map['username'] = $param['seller'];
              $seller = model('user')->infoData($map);
              if(empty($seller)){
                return error_json('卖家不存在');
              }
          //判断买家是否等于卖家

           if($param['buyer'] == $param['seller']){
            return error_json('买家和卖家不允许相同');
           }
           //判断交易价格
           if(empty($param['price']) || !is_numeric($param['price']) || strlen($param['price']) >10){
            return error_json('请填写正确的交易价格');    
          }
          if($param['price'] < 1){
            return error_json('交易价格至少1元');    
          }
                $data['cid'] = $param['cid'];
                $data['title'] = $param['title'];
                $data['buyer_uid'] = $buyer['uid']; //买家UID
                $data['buyer'] = $param['buyer'];
                $data['seller_uid'] = $seller['uid']; //卖家UID
                $data['seller'] = $param['seller'];
                $data['price'] = $param['price'];
                $data['fee_ratio'] = $this->settings['guarantee']['fee_ratio'];
                $data['fee_type'] = $param['fee_type'];
                $data['buyer_pay'] = $param['buyer_pay'];
                $data['seller_get'] = $param['seller_get'];      
                $data['content'] = $param['content'];
                $data['create_time'] = time();
                $data['status'] = isset($param['status'])?$param['status']:'';

                $result =  model('guarantee')->addData($data);
                if($result){
                    return success_json('中介交易创建成功');
                     
                  }else{
                     return error_json('添加失败');
                  }
                  

         }else{

              return $this->fetch();
         }


      return $this->fetch();
	}
// 编辑
	public function edit()
  {
     $param = input();
     if($this->request->isPost()){
             $param = input("post.");

               //表单验证
               $rule =[
                  'content'=>'require',
                ];
                $msg= [
                 'content.require' =>'担保交易内容不能为空',
                
                ];
                 $error = $this->checkSubmit($param,$rule,$msg);  
                if($error){
                    return error_json($error);
                 }

               //管理员强制验收

              if(!empty($param['shipping_status'])){
                $data['shipping_status'] = 2;
                $data['success_time'] = time();


              }
                $data['content'] = $param['content'];
                $data['id'] = $param['id'];
                $data['update_time'] = time();

                $data['status'] = isset($param['status'])?$param['status']:'';
                $where['id'] = $data['id'];
                $result =  model('guarantee')->editData($data,$where);
              if(!empty($param['shipping_status'])){
              //验收后给卖家打款 



                //获得订单信息
                $order = model('guarantee')->infoData(['id'=>$param['id']]);
                //给卖家打款
                model('user')->payin($order['seller_uid'],$order['seller_get'],'订单支付，订单号：'.$order['id'],"余额");
               
                model('message')->send($order['seller_uid'],'验收消息','您的订单号：'.$order['id'].',已经确认验收,您获得收入：'.$order['seller_get'].'元',"0");
              }
                if($result){
                    return success_json('更新成功');
                     
                  }else{
                     return error_json('更新失败');
                  }
                  

         }else{
              if(!$param['id']){  return error_json('请求参数错误');}
              $where['id'] = intval($param['id']);
              $guarantee = model('guarantee')->infoData($where);

           
              $this->assign('guarantee',$guarantee);
              

              if(($guarantee['order_status']== 0) && ($guarantee['pay_status']==0) && ($guarantee['shipping_status']==0)){
                //订单创建
                 $step =1;
              }else 
              if(($guarantee['order_status'] ==1) && ($guarantee['pay_status']==0) && ($guarantee['shipping_status']==0)){
                //卖家确认
                  $step =2;
              }else if(($guarantee['order_status'] ==1) && ($guarantee['pay_status']==1) && ($guarantee['shipping_status']==0)){
                //卖家发货
                $step =3;
              }else if(($guarantee['order_status'] ==1) && ($guarantee['pay_status']==1) && ($guarantee['shipping_status']==1)){
                //卖家确认
               $step =4;
              }else if(($guarantee['order_status'] ==1) && ($guarantee['pay_status']==1) && ($guarantee['shipping_status']==2)){
                //订单关闭
                $step =5;
              }else{
                $step = 0;
              }
              $this->assign('step',$step);
              
              return $this->fetch();
         }
  }
  //关闭订单
  public function close()
  {
    $param = $this->request->param();
    if(empty($param['id'])){
      return error_json('参数不存在'); 
    }
    $id = intval($param['id']);
    //订单管理
    $order = model('guarantee')->infoData(['id'=>$id]);
    //已经支付但是没有收货
    if($order['pay_status'] == 1 && $order['shipping_status'] < 2){
//关闭订单，退款给买家
    $data['order_status'] = 2;
    $data['pay_status'] =  0;
    $data['shipping_status'] =0;
    $where['id'] = $id;
    model('guarantee')->editData($data,$where);
   //退款给买家
    model('user')->payin($order['buyer_uid'],$order['buyer_pay'],'订单【'.$order['title'].'】已被管理员关闭,系统自动返还订单金额'.$order['buyer_pay'].'元');
    //给买家发送消息
    model('message')->send($order['buyer_uid'],'订单关闭消息','订单【'.$order['title'].'】已被管理员关闭,系统自动返还订单金额'.$order['buyer_pay'].'元');
    
    //给卖家发送消息
     model('message')->send($order['seller_uid'],'订单关闭消息','订单【'.$order['title'].'】已被管理员关闭');
   
   
    return success_json('关闭订单成功,并且已退款给买家');


    }else if($order['pay_status'] < 1 && $order['shipping_status'] < 2){
      //没有支付的直接关闭订单
      $data['order_status'] =2;
      $data['pay_status'] =  0;
      $data['shipping_status'] =0;
      $where['id'] = $id;
      model('guarantee')->editData($data,$where);
    //发送消息
    //给买家发送消息
    model('message')->send($order['buyer_uid'],'订单关闭消息','订单【'.$order['title'].'】已被管理员关闭');
    
    //给卖家发送消息
     model('message')->send($order['seller_uid'],'订单关闭消息','订单【'.$order['title'].'】已被管理员关闭');
   
      return success_json('关闭订单成功');
   
    }




  }
// 删除
	public function del()
  {
       $param = input();
       if(!$param['id']){  return error_json('请求参数错误');    }
       $where["id"] = $param['id'];
       $res= model('guarantee')->delData($where);
       if($res){
        return success_json('删除成功');
       }else{
        return error_json('删除失败');
       }     
	}
  //纠纷处理
  public function rights()
  {

       $alias = '';        //需要别名时写别名，不需要的时候留空 
      $param = $this->request->param();
      $status = !empty($param['SingleField'][0]['value'])?intval($param['SingleField'][0]['value']):'-1';
  
      $defaultOrder = 'create_time desc';  //默认排序
    //接收搜索表单数据
      $SearchFormData = $this->getSearchFormData($defaultWhere,$defaultOrder);
      $where = $SearchFormData['where'];
      
      $order = $SearchFormData['order'];
      $pageNum = $SearchFormData['pageNum'];
//组建关键词数据
     $keywordsData  =[
                  [
                  'field'   =>'id', //字段名
                  'name'    =>'维权ID', //文本显示名称
                  'alias'   => $alias,  //字段对应的别名
                  ],

     ];
//组建日期筛选   
       $dateData = [
                  [
                  'title'        =>'创建时间',  //标签显示名称
                  'field'        =>'create_time', //筛选字段
                  'start_name'   =>'开始时间', //开始时间
                  'end_name'     =>'结束时间', //结束时间
                  'alias'        => $alias,  //字段别名
                  ],

              ];
//单个字段筛选
    $customSingleField =[
                            [
                             'name'=>'维权状态',
                             'field' => 'status', 
                             'data'  => [ 0 =>'待处理',1=>'已处理',2=>'未成立'],
                             'alias'=>$alias,
                         
                            ]
                       ]; 
// 组件字段组筛选
     $groupData = [];
     $orderData   = [];  

     $this->assign('keywordsData',$keywordsData);
     $this->assign('customSingleField',$customSingleField);
     $this->assign('groupData',$groupData);
     $this->assign('dateData',$dateData);
     $this->assign('orderData',$orderData);


     $lists = DB::name('guaranteeRights')
     ->where($where)
     ->order($order)
     ->paginate($pageNum,false,['query' => request()->param()]);
     $page = $lists->render();
     $list = $lists->toArray()['data'];
     foreach($list as $k=>$v){
       $map['uid'] = $v['from_uid'];
       $from =  model('user')->infoData($map);
       $list[$k]['from_username'] = $from['username'];
       $map2['uid'] = $v['to_uid'];
        $to =  model('user')->infoData($map2);
       $list[$k]['to_username'] = $to['username'];    
     }

   
     $this->assign('page', $page);
     $this->assign('list', $list);
     return $this->fetch();
  }
  //维权处理
  public function Handle()
  {
    $param = $this->request->param();
     if($this->request->isAjax()){
              $id = intval($param['id']);
              $rights = model('guaranteeRights')->infoData(['id'=>$id]); //维权
              if($rights['status'] !=0){
                   return error_json('操作状态错误');
              }

              //通过维权id 获得订单
              $order_map['id'] = $rights['order_id'];
              $order = model('guarantee')->infoData($order_map);
             
              //获得交易信息
              $info_map['id'] = $order['info_id'];
              $info = model('guarantee')->infoData($info_map);  //交易信息

          //表单验证
          $rule =[
            'id'=>'require|number',
            'type'=>'require',
            'buyer_get'=>'require',
            'seller_get'=>'require',
            ];
            $msg= [
            'id.require' =>'请求参数不能为空',
            'id.number'   =>'请求参数格式错误',
            'type.require' =>'操作类型参数不能为空',
             'buyer_get.require' =>'买家分配金额不能为空',
            'seller_get.require' =>'卖家分配金额不能为空',
            
            ];
            $error = $this->checkSubmit($param,$rule,$msg);  
            if($error){
                return error_json($error);
            }
            $buyer_get     = $param['buyer_get']?$param['buyer_get']:0;
            $seller_get    = $param['seller_get']?$param['seller_get']:0;
              if(!is_numeric($param['seller_get'])){
                    return error_json('请输入正确卖家获得金额');
                  }
                if(!is_numeric($param['buyer_get'])){
                  return error_json('请输入正确的买家支付费用');
                }
              //判断买家价格是否小于总价格
                if($order['price'] != ($buyer_get + $seller_get)){
                  return error_json('分配的金额必须等于'.$order['price'].'元');
                }
                //判断买家最大分配金额必须小于买家支付金额
                if($buyer_get > $order['price']){
                  return error_json('给买家分配的金额不得大于实际支付的金额');
                }
                if($seller_get > $order['seller_get']){
                  return error_json('给卖家分配的金额不得大于实际获得的金额');
                }


             //获得仲裁结果数据    
                //来自买家
                if($rights['role'] ==0){
                  $map1['uid'] = $rights['from_uid'];
                  $buyerData = model('user')->infoData($map1);
                  $buyer =  $buyerData['username'];

                  $map2['uid'] = $rights['to_uid'];
                  $sellerData =model('user')->infoData($map2);
                  $seller =  $sellerData['username'];
                }else{
                  //来自卖家   
                  $map2['uid'] = $rights['from_uid'];
                  $sellerData =model('user')->infoData($map2);
                  $seller =  $sellerData['username'];

                  $map1['uid'] = $rights['to_uid'];
                  $buyerData = model('user')->infoData($map1);
                  $buyer =  $buyerData['username'];
                }
               $data['result'] = '订单【'.$rights['title'].'】纠纷处理结果：买家（'.$buyer.'）获得：'.$buyer_get.'元；卖家（'.$seller.'）获得：'.$seller_get.'元。'; //仲裁结果
              //买家维权  
               if($rights['role'] ==0){
                     // 买家加钱
                     model('user')->payin($rights['from_uid'],$buyer_get,$data['result']);
                     // 卖家加钱
                     model('user')->payin($rights['to_uid'],$seller_get,$data['result']);
                     //发送消息：纠纷处理结果
                     model('message')->send($rights['from_uid'],'纠纷处理结果',$data['result']);
                     model('message')->send($rights['to_uid'],'纠纷处理结果',$data['result']);
               }else{
  //卖家维权
                 //增加余额
                 $buyer_data['money'] = $buyer_get;
                 // 买家加钱
                 model('user')->payin($rights['to_uid'],$buyer_get,$data['result']);
                 // 卖家加钱
   
                 model('user')->payin($rights['from_uid'],$seller_get,$data['result']);
   
                 //发送消息：纠纷处理结果
                  model('message')->send($rights['to_uid'],'纠纷处理结果',$data['result']);
                  model('message')->send($rights['from_uid'],'纠纷处理结果',$data['result']);
               }
                 
                //关闭订单 
                $order_data['order_status'] = 2;
                $order_data['pay_status'] = 0;
                $order_data['shipping_status'] = 0;
                $order_where['id'] = $rights['order_id'];
                model('guarantee')->editData($order_data,$order_where);
 
               //关闭交易信息
               $info_data['status'] = 4; //交易关闭
               $info_where['id'] = $order['info_id'];
               model('guaranteeInfo')->editData($info_data,$info_where);

     if($param['type'] == 'success'){
// 处理成功
     
                 //判断卖家最大分配金额必须小于卖家最大收入金额
                 $data['buyer_get']  =  $buyer_get; //买家得到金额
                 $data['seller_get'] =  $seller_get; //卖家得到金额
                 $data['status']     = 1;
                 $data['audit_time'] = time();
                 
                 $where['id'] = $id;
                 $result =  model('guaranteeRights')->editData($data,$where);

                return success_json('维权处理成功');
        
  }else if($param['type'] == 'fail'){
      //未成立,修改维权状态，交易继续进行，不做分配金额处理
                $data['result']    = $param['value']; //失败原因
                $data['buyer_get']  = $param['buyer_get']; //买家得到
                $data['seller_get'] = $param['seller_get']; //卖家得到
 
                $data['status']     = 2;
                $data['pay_status'] = 0;
                $data['shipping_status'] = 0;
                $data['audit_time'] = time();
            
                $where['id'] = $id;

                $result =  model('guaranteeRights')->editData($data,$where);

                return success_json('维权处理成功');

          
            }
          

         }else{
              if(!$param['id']){  return error_json('请求参数错误');}
              $where['id'] = intval($param['id']);
              $rights = model('guaranteeRights')->infoData($where);

              $map['uid'] = $rights['from_uid'];
              $from =  model('user')->infoData($map);
              $rights['from_username'] = $from['username'];  //维权发起人
              $map2['uid'] = $rights['to_uid'];

              $to =  model('user')->infoData($map2);
              $rights['to_username'] = $to['username'];      //被维权人
              //获得订单信息          
              $map3['id'] = $rights['order_id'];
              $order = model('guarantee')->infoData($map3);
              $rights['order'] = $order;

  
             $this->assign('rights',$rights);

              return $this->fetch();
         }  

  }

  public function set()
  {

    return $this->fetch();
  }

   public  function category()
   {

      return parent::category();
   }

   public  function categoryAdd()
   {

      return parent::categoryAdd();
   }
   public  function categoryEdit()
   {

      return parent::categoryEdit();
   }
   public  function categoryUpdate()
   {

      return parent::updateCategoryCache();
   }
   public  function categoryDel()
   {

      return parent::del();
   }


  //交易信息
  public function info()
  {
      $param = $this->request->param();
      $alias = 'a';                    //需要别名时写别名，不需要的时候留空 
      $status = !empty($param['status'])?$param['status']:'all';
      switch($status){
        case '0':
         $defaultWhere = 'a.status =0';   //待审核
        break;
        case '1':
        $defaultWhere = 'a.status =1';  
        break;
        case '2':
        $defaultWhere = 'a.status =2';  
        break;
        case '3':
        $defaultWhere = 'a.status =3';  
        break;
        case '4':
        $defaultWhere = 'a.status = 4';  
        break;
        case '-1':
        $defaultWhere = 'a.status =-1';  
        break;
      }
      $defaultOrder = 'a.create_time desc';  //默认排序
      //接收搜索表单数据
      $SearchFormData = $this->getSearchFormData($defaultWhere,$defaultOrder);
      $where = $SearchFormData['where'];
      $order = $SearchFormData['order'];
      $pageNum = $SearchFormData['pageNum'];
    //组建关键词数据
     $keywordsData  =[
                  [
                  'field'   =>'id', //字段名
                  'name'    =>'交易ID', //文本显示名称
                  'alias'   => $alias,  //字段对应的别名
                  ],
                  [
                  'field'   =>'title',
                  'name'    =>'交易标题',
                  'alias'   => $alias,
                  ],
            
     ];
//组建日期筛选   
       $dateData = [
                  [
                  'title'        =>'创建时间',  //标签显示名称
                  'field'        =>'create_time', //筛选字段
                  'start_name'   =>'开始时间', //开始时间
                  'end_name'     =>'结束时间', //结束时间
                  'alias'        => $alias,  //字段别名
                  ],

              ];
//单个字段筛选
    $customSingleField =[
                            [
                             'name'=>'审核状态',
                             'field' => 'status', 
                             'data'  => [ 0 =>'待审核',1=>'待交易',2=>'交易中','3'=>'交易成功','4'=>'交易关闭','-1'=>'审核失败'],
                             'alias'=>$alias,
                            ] 
                       ]; 
// 组件字段组筛选
    $groupData = [];
     $orderData   = [
                 [
                 'name'     =>'交易价格多到少',
                 'field'    =>'price',  //字段名
                 'orderby'  =>'desc',     //排序
                 'alias'    => $alias,         //数据表别名
                 ],
                 [
                 'name'     =>'交易价格少到多',
                 'field'    =>'price',
                 'orderby'  =>'asc',
                 'alias'    => $alias,
                 ],
];  

     $this->assign('keywordsData',$keywordsData);
     $this->assign('customSingleField',$customSingleField);
     $this->assign('groupData',$groupData);
     $this->assign('dateData',$dateData);
     $this->assign('orderData',$orderData);


     $lists = DB::name('guarantee_info')->alias('a')
     ->join("guarantee_category b","a.cid = b.cid","LEFT")
     ->field("a.id,a.cid,a.id_type,a.title,a.price,a.username,a.fee_type,a.create_time,a.status,b.cname")
     ->where($where)
     ->order($order)
     ->paginate($pageNum);

     $page = $lists->render();
     $list = $lists->toArray()['data'];
     foreach($list as $k=>$v){
        $order =  model('guarantee')->infoData(['info_id'=>$v['id'],'order_status'=>1,'pay_status'=>1,]);
        $list[$k]['order'] = $order;
      }
     $this->assign('page', $page);
     $this->assign('list',$list);
     return $this->fetch();
  }
//增加
  public function infoAdd()
  {

     if($this->request->isPost()){
             $param = $this->request->param();
             $cate = $param['cate'];
               //表单验证
               $rule =[
                
                  'title'=>'require',
                  'username'=>'require',
                  'price'=>'require',
                  'fee_type'=>'require',
                  'id_type'=>'require',
                  'content'=>'require',
                ];
                $msg= [
                
                 'title.require' =>'请输入信息标题',
                 'username.require' =>'发布用户不能为空',
                 'price.require' =>'请输入交易价格',
                 'id_type.require' =>'请选择发布者身份',
                 'fee_type.require' =>'请选择中介费支付方式',
                 'content.require' =>'请输入商品内容',
                ];
 
                 $error = $this->checkSubmit($param,$rule,$msg);  
                 
                if($error){
                    return error_json($error);
                 }
                 if(empty($this->settings['guarantee']['fee_ratio'])){
                   return error_json('中介手续费没有配置');
                 }
                   $data['cid'] = $param['cid'];
                 if(empty($data['cid'])){
                   return error_json('请选择分类'); 
                 }
                // 判断卖家是否存在
                $map['username'] = $param['username'];
                $user = model('user')->infoData($map);
                if(empty($user)){
                  return error_json('发布者用户名不存在');
                }
                if(empty($param['price']) || !is_numeric($param['price']) || strlen($param['price']) >10){
                  return error_json('请填写正确的预期价格');    
                }
                if($param['price'] < 1){
                  return error_json('预期价格至少1元');    
                }
                $data['title']  = $param['title'];
                $data['uid']      = $user['uid'];
                $data['username'] = $user['username'];
                $data['id_type']  = $param['id_type']; 
                $data['price']  = $param['price'];
                $data['fee_ratio']  = $this->settings['guarantee']['fee_ratio'];
                $data['fee_type']   = $param['fee_type'];   
                $data['content']     = $param['content'];
                $data['create_time'] = time();
                $data['status'] = isset($param['status'])?$param['status']:0;

                $result =  model('guarantee_info')->addData($data);
                if($result){
                    return success_json('信息发布成功');
                     
                  }else{
                     return error_json('信息发布失败');
                  }
                  

         }else{

              return $this->fetch();
         }


      return $this->fetch();
  }
// 编辑
  public function infoEdit()
  {
      $param = $this->request->param();
     if($this->request->isPost()){
                     //表单验证
                     $rule =[
                
                      'title'=>'require',
                      'username'=>'require',
                      'price'=>'require',
                      'fee_type'=>'require',
                      'id_type'=>'require',
                      'content'=>'require',
                    ];
                    $msg= [
                    
                     'title.require' =>'请输入信息标题',
                     'username.require' =>'发布用户不能为空',
                     'price.require' =>'请输入交易价格',
                     'id_type.require' =>'请选择发布者身份',
                     'fee_type.require' =>'请选择中介费支付方式',
                     'content.require' =>'请输入交易内容',
                    ];
                 $error = $this->checkSubmit($param,$rule,$msg);  
                if($error){
                    return error_json($error);
                 }

              // 判断卖家是否存在
              $map['username'] = $param['username'];
              $user = model('user')->infoData($map);
              if(empty($user)){
                return error_json('发布用户名不存在');
              }

              if(empty($param['price']) || !is_numeric($param['price'])|| $param['price']<=0 || strlen($param['price']) >10){
                return error_json('请填写正确的交易价格');    
              }
      
              $data['id'] = $param['id'];
              $data['title']  = $param['title'];
              $data['uid']      = $user['uid'];
              $data['username'] = $user['username'];
              $data['id_type']  = $param['id_type']; 
              $data['price']  = $param['price'];
              $data['fee_ratio']  = $this->settings['guarantee']['fee_ratio'];
              $data['fee_type']   = $param['fee_type'];   
              $data['content']     = $param['content'];
              $data['create_time'] = time();
              $data['status'] = isset($param['status'])?$param['status']:0;

               
                $data['update_time'] = time();

                $data['status'] = isset($param['status'])?$param['status']:'';
                $where['id'] = $data['id'];
                $result =  model('guarantee_info')->editData($data,$where);
                if($result){
                    return success_json('信息更新成功');
                     
                  }else{
                     return error_json('信息更新失败');
                  }
                  

         }else{
               if(!$param['id']){  return error_json('请求参数错误');}
              $where['id'] = intval($param['id']);
              $guaranteeinfo = model('guarantee_info')->infoData($where);
              //获取成交的订单
               $map['info_id'] = intval($param['id']);
               $map['order_status'] = 1;
               $map['pay_status'] = 1;
               $order = model('guarantee')->infoData($map);
     
              $guaranteeinfo['order'] = $order;

              $this->assign('guaranteeinfo',$guaranteeinfo);
              return $this->fetch();
         }
  }
// 交易信息删除
  public function infoDel()
  {
     return $this->delData('guarantee_info','id');
  }


// 维权删除
  public function rightsDel()
  {
     return $this->delData('guarantee_rights','id');
  }


}